import os
import subprocess
import shutil
from conn_pool import get_redis

rs = get_redis()


def iter_files(root_dir, app, device):
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            file_name = os.path.join(root, file)
            tmp = app + '/' + device
            if tmp in file_name and file_name.endswith('.jpg'):
                print(file_name)


def redis_test():
    rs.flushall()
    rs.set('xxmm', '11')
    print(rs.get('xxmm'))
    rs.set('xxmm', '22')
    print(rs.get('xxmm'))


def delete_dir_test():
    shutil.rmtree('../static/aaa')


def adb_test():
    adb_path_command = """
        mdfind -name "platform-tools" | grep "Android/sdk/platform-tools" | awk '{print $1}'
    """
    adb_path_process = subprocess.Popen(
        adb_path_command,
        shell=True, close_fds=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    adb_path_process.wait()
    adb_path = adb_path_process.stdout.read().decode('utf-8')
    devices_command = """
        %s/adb devices | grep -Ev "List of devices attached" | awk '{print $1}' > %s/devices_list.conf
    """ % (
        adb_path.replace('\r', '').replace('\n', '').replace('\r\n', ''), os.path.dirname(os.path.abspath(__file__)),)
    devices_process = subprocess.Popen(
        devices_command,
        shell=True, close_fds=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    devices_process.wait()


if __name__ == '__main__':
    # iter_files('../static', 'shuabao', 'M960BDPT226TA')
    # adb_test()
    from conn_pool import get_redis, REDIS_APP_RUN_LOG

    rs = get_redis()

    while True:
        msg = rs.lpop(REDIS_APP_RUN_LOG)
        if msg is not None:
            print(msg)
